<template>
  <div class="account-info">
    <h2>账号管理</h2>
    <el-form
        :model="accountForm"
        :rules="rules"
        ref="accountFormRef"
        label-width="120px"
        class="account-form"
    >
      <div class="avatar-section">
        <Upload :src="accountForm.avatarUrl"
                :previewImage="previewImage"
                :handleAvatarChange="handleAvatarChange"
                :before-avatar-upload="beforeAvatarUpload"/>
        <p class="avatar-tip">支持JPG/PNG格式，大小不超过2MB</p>
      </div>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="accountForm.username"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <div style="display: flex">
          <div style="flex: 2">
            <el-input v-model="accountForm.email" style="width: 280px"></el-input>
          </div>
          <div style="flex: 1; margin-left: 15px;">
            <el-button type="primary" plain @click="verifyEmail" v-if="!accountForm.emailVerified">
              验证邮箱
            </el-button>
            <el-tag type="success" v-else>已验证</el-tag>
          </div>
        </div>

      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <div style="display: flex">
          <div style="flex: 2">
            <el-input v-model="accountForm.phone" style="width: 280px"></el-input>
          </div>
          <div style="flex: 1; margin-left: 15px;">
            <el-button type="primary" plain @click="verifyPhone" v-if="!accountForm.phoneVerified">
              验证手机
            </el-button>
            <el-tag type="success" v-else>已验证</el-tag>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="旧密码" prop="username">
        <el-input v-model="accountForm.password"></el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="accountForm.newPassword" show-password></el-input>
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="accountForm.confirmPassword" show-password></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { userInform } from '@/stores/userInform'
import { ElMessage } from 'element-plus'
import Upload from "@/components/Upload.vue";

const userStore = userInform()
const accountFormRef = ref(null)

// 预览图片
const previewImage = ref('');

// 头像上传处理
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}

// 处理头像选择变化
const handleAvatarChange = async (file) => {
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件!');
    return false;
  }

  // 验证文件大小
  const isLt2M = file.raw.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }

  const response = await PostFileUserImg(file.raw);
  if(response.data.code !== 200){
    ElMessage.error(response.data.message);
    return;
  }
  form.avatarUrl = response.data.data;

  // 创建预览图
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);

  return false; // 阻止自动上传
};

const accountForm = reactive({
  avatarUrl: userStore.avatarUrl || '',
  username: userStore.username || '',
  email: userStore.email || '',
  emailVerified: false,
  phone: userStore.phone || '',
  phoneVerified: true,
  password: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value !== accountForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = reactive({
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
  ],
  confirmPassword: [
    { validator: validatePass, trigger: 'blur' }
  ]
})

const verifyEmail = () => {
  // 发送验证邮件逻辑
  ElMessage.success('验证邮件已发送，请查收')
}

const verifyPhone = () => {
  // 发送验证短信逻辑
  ElMessage.success('验证码已发送，请查收')
}

const submitForm = () => {
  accountFormRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
    } else {
      return false
    }
  })
}
</script>

<style>
.account-info {
  padding: 20px;
}

.avatar-section{
  margin-left: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 270px;
  margin-bottom: 28px;
}

.avatar-uploader{
  width: 178px;
  height: 178px;
  margin-bottom: 10px;
}

.avatar-uploader .avatar{
  border-radius: 50%;
}

.el-upload{
  width: 100%;
  height: 100%;
  border-radius: 50%;
  margin-bottom: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.account-form {
  max-width: 600px;
  margin-top: 20px;
}
</style>
